package com.snapan.service.impl;

import com.snapan.dao.FileBaseDao;
import com.snapan.entity.FileBase;
import com.snapan.service.FileBaseService;
import com.snapan.vo.CheckUploadVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 文件基础信息表服务实现类
 */
@Service
@Transactional
public class FileBaseServiceImpl implements FileBaseService {

    @Autowired
    private FileBaseDao filebaseDao;

    @Override
    public FileBase getById(Long id) {
        return filebaseDao.selectById(id);
    }

    @Override
    public List<FileBase> getAll() {
        return filebaseDao.selectAll();
    }

    @Override
    public boolean add(FileBase filebase) {
        return filebaseDao.insert(filebase) > 0;
    }

    @Override
    public boolean update(FileBase filebase) {
        return filebaseDao.update(filebase) > 0;
    }

    @Override
    public boolean delete(Long id) {
        return filebaseDao.deleteById(id) > 0;
    }

    @Override
    public CheckUploadVo checkUpload(FileBase filebase) {
        CheckUploadVo vo = new CheckUploadVo();
        filebase = filebaseDao.checkUpload(filebase);
        if(filebase != null){
            vo.setUploaded(true);
            vo.setUrl(filebase.getFilePath());
//            if(filebaseDao.checkUploadlist(filebase.getId()) == filebase.getChunkCount());
            List<Integer> list = filebaseDao.checkUploadlist(filebase.getId());
            Set<Integer> set = new HashSet<>(list);
            int totalChunk = filebase.getChunkCount();
            List<Integer> falseList = new ArrayList<>();
            for(int i =1 ; i <= totalChunk; i++){
                if (!set.contains(i)) {
                    falseList.add(i);
                }
            }
            vo.setChunkUploaded(falseList);
        }else{
            vo.setUploaded(false);
        }
        return vo;
    }

    @Override
    public CheckUploadVo checkUpload(String fileName, Long fileSize, String fileMD5) {
        CheckUploadVo vo = new CheckUploadVo();
        FileBase fileBase = getByMD5AndSize(fileMD5, fileSize);
        if (fileBase != null && fileBase.getStatus() == 1) {
            vo.setUploaded(true);
            vo.setUrl(fileBase.getFilePath());
        } else {
            vo.setUploaded(false);
        }
        return vo;
    }

    @Override
    public FileBase getByMD5AndSize(String fileMD5, Long fileSize) {
        return filebaseDao.selectByMD5AndSize(fileMD5, fileSize);
    }

}
